package com.baosight.sczx.zm.cg.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.StaticBlocks;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.Department;
import com.baosight.sczx.common.zm.cInterface.cs.Engineering;
import com.baosight.sczx.common.zm.cInterface.cs.WorkSchedule;
import com.baosight.sczx.zm.ch.domain.ZMCHMineReport;
import com.baosight.sczx.zm.cs.domain.ZMCSWorkSchedule;
import com.baosight.sczx.zm.cg.domain.ZMCGDispatchDaily;

/**
 * 采煤进度汇报（调度日报用）
 * <p>Title: ServiceZMCG83.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张志芳
 * @version 1.0
 * <pre>Histroy:
 *          2011-9-6 下午02:24:59  张志芳  Create
 *</pre>
 */
public class ServiceZMCG83 extends ServiceEPBase {
	/**
	 * 初始化
	 * <p>Function: initLoad</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCP70</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午03:53:52 张志芳
	 * </p>
	 *
	 */
	@Override
	public EiInfo initLoad(EiInfo inInfo) {
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的		
		EiInfo outInfo = this.query(inInfo);
		return outInfo;
	}
	
	/**
	 * 查询
	 * <p>Function: query</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCP70</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午03:58:03 张志芳
	 * </p>
	 *
	 */
	@Override
	public EiInfo query(EiInfo inInfo) {
		
		StaticTools.setQueryParameters(inInfo, "fdMiningId", UserSession.getInSessionProperty("miningCode"), true);
		EiInfo outInfo = super.query(inInfo, "ZMCHMineReport.queryReport", new ZMCHMineReport());
	
		outInfo.addBlock(Engineering.getPlanEngineering("cmes.cp.engineering", "0", "2"));
		outInfo.addBlock(WorkSchedule.getWorkScheduleBlock("cmes.cp.workNum", false));//班次
		outInfo.addBlock(StaticBlocks.getStauts4());//状态
		outInfo.addBlock(Department.getInstance().getMiningDepts("cmes.cp.department", "orgCode", "orgName", false,UserSession.getInSessionProperty("miningCode").toString()));
		outInfo.set("userId", UserSession.getUserId());
		outInfo.set("userName", UserSession.getInSessionProperty("UserCname"));
		outInfo.set("departmentId", UserSession.getInSessionProperty("orgCode"));
		outInfo.set("departmentName", UserSession.getInSessionProperty("orgName"));
		outInfo.set("fdCreatorId", UserSession.getUserId());//登录人的默认值
		outInfo.set("fdMiningId", UserSession.getInSessionProperty("miningCode"));//矿ID的默认值
		outInfo.set("fdMiningName", UserSession.getInSessionProperty("miningName"));//矿名称的默认值
		
		return outInfo;
	}
	
	/**
	 * 新增
	 * <p>Function: insert</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCP70</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午03:58:15 张志芳
	 * </p>
	 *
	 */ 
	@Override
	public EiInfo insert(EiInfo inInfo) {	
		EiInfo out=new EiInfo();
		ZMCHMineReport _dom = new ZMCHMineReport();	
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		int i = 0;		
		for (; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			Map<String, String>	params = new HashMap<String, String>();
			String fdStatus = "上报";			
			boolean validate = validate(inInfo, _dom,"ZMCHMineReport.validate",params);
			if(validate) {
				inInfo = this.query(inInfo);
				return inInfo;
			}
			else {
				_dom.setFdStatus(fdStatus);
				_dom.setFdKeyId(TablePk.getInstance().getNextValue("T_CH_MINEREPORT"));//主键
				_dom.setFdMiningId(UserSession.getInSessionProperty("miningCode").toString());	//矿井id
				_dom.setFdMiningName(UserSession.getInSessionProperty("miningName").toString());// 矿井名称
				_dom.setFdReportDepartmentId(UserSession.getInSessionProperty("orgCode").toString());// 汇报部门id
				_dom.setFdReportDepartment(UserSession.getInSessionProperty("orgName").toString());// 汇报部门
				_dom.setFdReporterId(UserSession.getUserId().toString());// 汇报人ID
				_dom.setFdReporter(UserSession.getInSessionProperty("UserCname").toString());// 汇报人				
				_dom.setFdVirtualDate(WorkSchedule.getVirtualDate(_dom.getFdCurrentDate(),_dom.getFdWorknumId()));
				this.dao.insert("ZMCHMineReport.insert",_dom);
			}
		}
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out; 	

} 

	/**
	 * 修改
	 * <p>Function: update</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCP70</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午03:58:24 张志芳
	 * </p>
	 *
	 */
	@Override
	public EiInfo update(EiInfo inInfo) {
		EiInfo out = new EiInfo();
		ZMCHMineReport _dom = new ZMCHMineReport();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		int i = 0;
		for (; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			Map<String, String>	params = new HashMap<String, String>();
			params.put("fdKeyId", _dom.getFdKeyId());
			
			boolean validate = validate(inInfo, _dom,"ZMCHMineReport.validate",params);
			if(validate) {
				out = this.query(inInfo);
				return out;
			}
			else {
				this.dao.update("ZMCHMineReport.update",_dom);
			}
		}
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out;	
			
	}		
			
	
	/**
	 * 删除
	 * <p>Function: delete</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCP70</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午03:58:35 张志芳
	 * </p>
	 *
	 */
	@Override
	public EiInfo delete(EiInfo inInfo) {
		EiInfo out=new EiInfo(); 
		ZMCHMineReport _dom = new ZMCHMineReport();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		int i = 0;
		for (; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			String message = validateBeforeDelete(_dom);
			if("".equals(message))
				dao.delete("ZMCHMineReport.delete", _dom);			
			else{
				out = this.query(inInfo);
				out.setStatus(1);
				out.setMsg(message);
				return out;
			}
		}
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out;   
	}
	
	private String validateBeforeDelete(ZMCHMineReport _dom) {
		// TODO Auto-generated method stub
		String  keyid  =  _dom.getFdKeyId();
		String reporterId = UserSession.getUserId().toString();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("fdKeyId", keyid);
		params.put("fdReporterId", reporterId);
		List result = dao.query("ZMCHMineReport.validateBeforeDelete", params);
		if(result != null && result.size() > 0) 
			return "只能删除自己录入的数据，可以用“退回”按钮将数据退回给创建者！";
		return "";
	}

	/**
	 * 上报
	 * <p>Function: report</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午04:07:27 张志芳
	 *    2016年8月25日17:56:29 王伟 修改
	 *    修改内容为：在上报的同时更新调度生产日报表中的累计值
	 * </p>
	 *
	 */
	public EiInfo report(EiInfo inInfo)
	{
		EiInfo out=new EiInfo(); 
		ZMCHMineReport _dom = new ZMCHMineReport();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		int count = 0;
		for (int i = 0; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			if(!"已发布".equals(_dom.getFdStatus()))
			{
				_dom.setFdStatus("已发布");
				this.dao.update("ZMCHMineReport.report",_dom);
				
	            String fdWorknumId = _dom.getFdWorknumId();
				String fdVirtualDate = _dom.getFdVirtualDate();
				String fdMiningId = _dom.getFdMiningId();
				String fdMiningName = _dom.getFdMiningName();			
				DailyReport.generateMine(fdWorknumId, fdVirtualDate, fdMiningId, fdMiningName);
				count++;
			}
		}	
		out = this.query(inInfo);
		out.setStatus(1);
		if(count == rowcount)
		    out.setMsg("操作" + count + "条记录成功");
		else
			out.setMsg("操作" + count + "记录成功,未成功"+Integer.valueOf(rowcount-count).toString()+"条记录.原因是不能发布状态为“已发布”的数据！");
		return out;    
	}
	/**
	 * 撤回
	 * <p>Function: update</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCP70</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午03:58:24 张志芳
	 * </p>
	 *
	 */
	public EiInfo goback(EiInfo inInfo) {
		EiInfo out = new EiInfo();
		ZMCHMineReport _dom = new ZMCHMineReport();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		int count = 0;
		for (int i = 0; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			if("已发布".equals(_dom.getFdStatus())){
				_dom.setFdStatus("上报");
				dao.update("ZMCHMineReport.report",_dom);
				
	            String fdWorknumId = _dom.getFdWorknumId();
				String fdVirtualDate = _dom.getFdVirtualDate();
				String fdMiningId = _dom.getFdMiningId();
				String fdMiningName = _dom.getFdMiningName();			
				DailyReport.generateMine(fdWorknumId, fdVirtualDate, fdMiningId, fdMiningName);
				count++;
			}else{
				String userId = UserSession.getUserId().toString();
				
				if(!userId.equals(_dom.getFdReporterId())){
					_dom.setFdStatus("草拟");
					dao.update("ZMCHMineReport.report",_dom);
					count++;
				}	
			}
		}
		out = this.query(inInfo);
		out.setStatus(1);
		if(count == rowcount)
		    out.setMsg("操作" + count + "条记录成功");
		else
			out.setMsg("操作" + count + "记录成功,未成功"+Integer.valueOf(rowcount-count).toString()+"条记录.原因是不能撤回自己录入的状态为“已上报”的数据！");
		return out;	
			
	}		

	/**
	 * 校验是否重复
	 * <p>Function: validate</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-16下午12:48:34 张志芳
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes" })
	private boolean validate(EiInfo inInfo, ZMCHMineReport _dom, String sqlName, Map<String, String> params) {
		if(params == null) {
			params = new HashMap<String, String>();
		}
		String fdWorknumId = _dom.getFdWorknumId();
		String fdMiningId = _dom.getFdMiningId();
		String fdCurrentDate = _dom.getFdCurrentDate();
		String fdReportDepartmentId = _dom.getFdReportDepartmentId();
		
		params.put("fdWorknumId", fdWorknumId);
		params.put("fdMiningId", fdMiningId);
		params.put("fdCurrentDate", fdCurrentDate);
		params.put("fdReportDepartmentId", fdReportDepartmentId);
		
		List result = dao.query("ZMCHMineReport.validate", params);
		if(result != null && result.size() > 0) {
			inInfo.setStatus(-1);
			String msg = "采煤进度汇报每部门每天每班只能填写一份！";
			inInfo.setMsg(msg);
			return true;
		}
		return false;
	
	}	
}	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	